package com.example.listossimage.aop;

import com.example.listossimage.util.IpAdrressUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 切面类
 */
@Aspect
@Component
public class LogAspect {

    @Pointcut("@annotation(com.example.listossimage.aop.LogInfo)")
    public void logPointCut() {}

    @Around("logPointCut()")
    public Object logAround(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ipAdrress = IpAdrressUtil.getIpAdrress(request);
        String localName = request.getLocalName();
        System.out.println(ipAdrress);
        System.out.println(localName);
        Object[] args = joinPoint.getArgs();
        //通过反射来获取注解内容
        LogInfo logInfo = signature.getMethod().getAnnotation(LogInfo.class);
        String value = logInfo.value();
        System.out.println("value:" + value);
        Object result = null;

        long start = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
        }catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        return result;
    }

}
